package Pakke;

import java.awt.*;
import java.awt.event.*;
import java.io.*;
import javax.swing.*;
import javax.swing.event.*;
import static javax.swing.JOptionPane.*;


/**
 * 
 * @author maria
 * FancyTimerGuiSettingsNotifications.java
 *
 * Klassen fokuserer på GUI i alarmsettingstaben.
 */

public class FancyTimerGuiSettingsNotifications extends JPanel {

    private final String leftBoxTitle = "Notifications";
    private final String rightBoxTitle = "Notification details";

    private FancyTimerLogikk fancyTimerLogikk;
    private Box venstreBoks;
    private Box hoyreBoks;
    private Box storBoks;
    private String newButtonString = "New";
    private String deleteButtonString = "Delete";
    private String editButtonString = "Edit";
    private String browseButtonString = "Browse...";
    private String finishedButtonString = "Save";
    private ButtonListener buttonListener = new ButtonListener();
    private ListListener listListener = new ListListener();
    private Font font = new Font("Century Gothic", Font.BOLD, 12);
    private ComboBoxListener comboBoxListener = new ComboBoxListener();
    private final int MAIL = 0, TWITTER = 1, SOUND = 2;
    private Box hovedboks;


    /**
     *
     * @param fancyTimerLogikk
     */
    public FancyTimerGuiSettingsNotifications(FancyTimerLogikk fancyTimerLogikk) {
        setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
        this.fancyTimerLogikk = fancyTimerLogikk;
        hovedboks = setUpFrames();
        this.add(hovedboks);
    }

    /**
     * Metoden setter opp alle bokser, venstreBoks og hoyreBoks plasseres inne i storBoks
     * @return En "stor", horisontal boks som inneholder to vertikale bokser (med innhold)
     */
    public Box setUpFrames() {
        storBoks = Box.createHorizontalBox();
        

        venstreBoks = FancyTimerStatic.createVerticalBox(leftBoxTitle);
        venstreBoks.add(new NotifListPanel(-1));
        venstreBoks.add(new ButtonPanel());

        hoyreBoks = FancyTimerStatic.createVerticalBox(rightBoxTitle);
        hoyreBoks.add(new InfoLabelPanel(-1));

        storBoks.add(venstreBoks);
        storBoks.add(hoyreBoks);

        return storBoks;
    }

    /**
     * Oppdaterer den "store" boksen (som inneholder to vertikale bokser)
     */
    public void refreshNotifications() {
            remove(hovedboks);
            hovedboks = setUpFrames();
            add(hovedboks);
    }

    /**
     * Fjerner og legger til ny boks på hoyresiden med informasjon om valgt timer,
     * @param valg Hver varsling har en ID i JListen og boksen oppdateres etter hvilken varsling man trykker på.
     */
    private void updateRightBox(int valg) {
        storBoks.remove(hoyreBoks);
        hoyreBoks.removeAll();
        hoyreBoks = FancyTimerStatic.createVerticalBox(rightBoxTitle);
        hoyreBoks.add(new InfoLabelPanel(valg));
        storBoks.add(hoyreBoks);
        validate();
    }
    /**
     * Fjerner og legger til ny boks i høyreside for editering.
     * Hvis man vil ha en tom boks, er parameter -1.
     * @param Hver varsling har en ID i JListen og boksen oppdateres etter hvilken varsling man trykker på.
     *
     */
    private void updateRightBoxEdit(int valg) {
        storBoks.remove(hoyreBoks);
        hoyreBoks.removeAll();
        hoyreBoks = FancyTimerStatic.createVerticalBox(rightBoxTitle);
        hoyreBoks.add(new EditNotificationPanel(valg));
        storBoks.add(hoyreBoks);
        validate();
    }
    /**
     * Dette er panelet for å endre på en varsling. Innholdet tegnes i høyreruta.
     */
    private class EditNotificationPanel extends JPanel {
        private String[] data;
        private JTextField notificationName;
        private JComboBox typeList;
        private JTextField epostField;
        private JTextField twitterUserName;
        private JTextField phoneNr;
        private JTextField filePath;
        private JPanel centerPanel;

        private JButton browseButton;
        private JPanel southPanel;
        private Component spacing;

        @Override
        public String getName() {
            return notificationName.getText().trim();
        }

        public String getEpostField() {
            return epostField.getText().trim();
        }

        public String getTwitterUserName() {
            return twitterUserName.getText().trim();
        }

        public String getPhoneNr() {
            return phoneNr.getText().trim();
        }

        public String getData() {
            return data[0];
        }

        public int getTypeList() {
            return typeList.getSelectedIndex();
        }

        /**
         *
         * @param valg ID'en til en varsling i JListen over varslinger. -1 gir tom boks.
         */
        public EditNotificationPanel(int valg) {
           setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
           
            setPreferredSize(new Dimension(280,275));

            JPanel northPanel = new JPanel();
            northPanel.setLayout(new GridLayout(2,2));

            centerPanel = new JPanel();
            centerPanel.setLayout(new GridLayout(2,1));

            southPanel = new JPanel();
            southPanel.setLayout(new GridLayout(1,2));
            
            if (valg == -1) {
               data = new String[3];
               data[0] = "";
               data[1] = "Sound";
               data[2] = "";
           }
           else data = fancyTimerLogikk.getNotificationInfo(valg);


            JLabel leadingText = new JLabel("Name");
            leadingText.setFont(font);
            notificationName = new JTextField(data[0]);
            JLabel typeLabel = new JLabel("Notification type");
            typeLabel.setFont(font);
            String[] types = {"Mail", "Twitter", "Sound"};
            typeList = new JComboBox(types);
            typeList.setSelectedIndex(findSelection(data[1]));
            typeList.addActionListener(comboBoxListener); // OMG HELT FEIL
            northPanel.add(leadingText);
            northPanel.add(notificationName);
            northPanel.add(typeLabel);
            northPanel.add(typeList);
            
            browseButton = new JButton(browseButtonString);
            browseButton.addActionListener(buttonListener);
            
            if(typeList.getSelectedIndex() == MAIL) {
                epostField = new JTextField(data[2]);
                leadingText = new JLabel("Email address:");
                centerPanel.add(leadingText);
                centerPanel.add(epostField);
                

                twitterUserName = new JTextField("");
                filePath = new JTextField("");
                filePath.setEditable(false);

            } else if(typeList.getSelectedIndex() == TWITTER) {
                twitterUserName = new JTextField(data[2]);
                leadingText = new JLabel("Tweet account:");
                centerPanel.add(leadingText);
                centerPanel.add(twitterUserName);

                epostField = new JTextField("");
                filePath = new JTextField("");
                filePath.setEditable(false);

            } else if(typeList.getSelectedIndex() == SOUND){
                filePath = new JTextField(data[2]);
                filePath.setEditable(false);
                centerPanel.add(filePath);
                centerPanel.add(browseButton);

                epostField = new JTextField("");
                twitterUserName = new JTextField("");

            }

            JButton finishedButton = new JButton(finishedButtonString);
            finishedButton.addActionListener(buttonListener);

            southPanel.add(finishedButton);
            southPanel.add(new JLabel(""));

            add(northPanel);
            add(Box.createRigidArea(new Dimension(1,40)));
            add(centerPanel);
            spacing = Box.createRigidArea(new Dimension(1,40));
            add(spacing);
            add(southPanel);
       }

        /**
         * Metoden finner ut om man har valgt mail, twitter eller sound som alarm.
         * @param string
         * @return
         */
        private int findSelection(String string) {
            if (string.equals("Mail")) return 0;
            if (string.equals("Twitter")) return 1;
            if (string.equals("Sound")) return 2;
            return 0;
        }

        /**
         * Metoden setter sti til en fil.
         * @param browseForFile
         */
        private void setFilePath(String browseForFile) {
            filePath.setText(browseForFile);
        }

        /**
         * Metoden tegner om midtpanelet på editpanelet slik at det som vises der
         * avhenger av hva man har trykket på JComboBox av alarmer.
         * @param selectedType ID til alarmene i JComboBox.
         */
        private void redrawMiddlePane(int selectedType) {
           remove(southPanel);
           remove(spacing);
           remove(centerPanel);
           centerPanel.removeAll();
           centerPanel = new JPanel();
           centerPanel.setLayout(new GridLayout(2,1));
           if (selectedType == MAIL) {
            JLabel leadingText = new JLabel("Email address:");
            leadingText.setFont(font);
            centerPanel.add(leadingText);
            centerPanel.add(epostField);
           }
           if (selectedType == TWITTER) {
            JLabel leadingText = new JLabel("Twitter username:");
            leadingText.setFont(font);
            centerPanel.add(leadingText);
            centerPanel.add(twitterUserName);
           }
           if (selectedType == SOUND) {
            centerPanel.add(filePath);
            centerPanel.add(browseButton);
           }
           add(centerPanel);
           add(spacing);
           add(southPanel);
           validate();
        }

       /**
        *
        * @return filePath Sti til en fil man ønsker som lyd-alarm.
        */
        private String getFilePath() {
            return filePath.getText().trim();
        }
   }

    /**
     * Inneholder JListen som man velger varslinger fra
     */
    private class NotifListPanel extends JPanel {
        /**
         * Legger til JListen med varslinger i JPanel
         * @param valg
         */
        public NotifListPanel(int valg) {
            setLayout(new GridLayout(1,1));
            JList notifList = createJListWithNotifications();
            JScrollPane timerListScroll = new JScrollPane(notifList);
            notifList.setFont(font);
            add(timerListScroll);
        }

        /**
         * Metoden lager en JList med varslinger.
         * @return En JList med varslinger
         */
        private JList createJListWithNotifications() {
            JList notifList = new JList(fancyTimerLogikk.getNotificationList());
            notifList.setSelectionMode(ListSelectionModel.SINGLE_SELECTION);
            notifList.setSize(500, 600);
            notifList.addListSelectionListener(listListener);
            return notifList;
        }

    }

    /**
     * Viser info om forskjellige varslinger
     */
    private class InfoLabelPanel extends JPanel {
        private String[] data;
        private JTextField notificationName;
        private JTextField epostField;
        private JTextField twitterUserName;
        private JTextField filePath;

        /**
         * 3 paneler opprettes og legges inn i et "stort" panel. Alle panelene
         * benytter seg av GridLayout. Info om varslingene er fordelt på de 3 panelene.
         * @param valg Hver varsling har en ID slik at man får info om den varslingen man velger fra lista.
         */
        public InfoLabelPanel(int valg) {
           setLayout(new BoxLayout(this, BoxLayout.Y_AXIS));
           
            setPreferredSize(new Dimension(280,275));

            JPanel northPanel = new JPanel();
            northPanel.setLayout(new GridLayout(2,2));

            JPanel centerPanel = new JPanel();
            centerPanel.setLayout(new GridLayout(2,1));

            JPanel southPanel = new JPanel();
            southPanel.setLayout(new GridLayout(1,2));
            
            if (valg == -1) {
               data = new String[3];
               data[0] = "";
               data[1] = "Sound";
               data[2] = "";
           }
           else data = fancyTimerLogikk.getNotificationInfo(valg);


            JLabel leadingText = new JLabel("Name");
            leadingText.setFont(font);
            notificationName = new JTextField(data[0]);
            notificationName.setEditable(false);
            JLabel typeLabel = new JLabel("Notification type");
            typeLabel.setFont(font);
            JTextField typeList = new JTextField(data[1]);
            northPanel.add(leadingText);
            northPanel.add(notificationName);
            northPanel.add(typeLabel);
            northPanel.add(typeList);

            
            if(typeList.getText().equals("Mail")) {
                epostField = new JTextField(data[2]);
                leadingText = new JLabel("Email address:");
                epostField.setEditable(false);
                centerPanel.add(leadingText);
                centerPanel.add(epostField);
            } else if(typeList.getText().equals("Twitter")) {
                twitterUserName = new JTextField(data[2]);
                leadingText = new JLabel("Tweet account:");
                twitterUserName.setEditable(false);
                centerPanel.add(leadingText);
                centerPanel.add(twitterUserName);
            } else if(typeList.getText().equals("Sound")){
                filePath = new JTextField(data[2]);
                filePath.setEditable(false);
                JButton browseButton = new JButton(browseButtonString);
                browseButton.addActionListener(buttonListener);
                browseButton.setVisible(false);
                centerPanel.add(filePath);
                centerPanel.add(browseButton);
            }

            JButton finishedButton = new JButton(finishedButtonString);
            finishedButton.addActionListener(buttonListener);
            finishedButton.setVisible(false);

            southPanel.add(finishedButton);
            southPanel.add(new JLabel(""));

            add(northPanel);
            add(Box.createRigidArea(new Dimension(1,45)));
            add(centerPanel);
            add(Box.createRigidArea(new Dimension(1,45)));
            add(southPanel);
       }


   }

   /**
    * Knappepanel, inneholder de 3 knappene på venstresida; "new", "edit" og "delete".
    */
    private class ButtonPanel extends JPanel {
        /**
         * Oppretter knappene og legger de til i JPanel
         */
        public ButtonPanel() {  
          //  Standard layouthåndterer FlowLayout
          //  ButtonListener buttonListener = new ButtonListener();

            JButton newButton = new JButton(newButtonString);
            newButton.setFont(font);
            newButton.addActionListener(buttonListener);
            add(newButton);

            JButton editButton = new JButton(editButtonString);
            editButton.setFont(font);
            editButton.addActionListener(buttonListener);
            add(editButton);

            JButton deleteButton = new JButton(deleteButtonString);
            deleteButton.setFont(font);
            deleteButton.addActionListener(buttonListener);
            add(deleteButton);
        }

        
    }

    /**
     * Lytter til klikk i JComboBox
     */
    private class ComboBoxListener implements ActionListener {
        private int selectedType;

        /**
         * Når man klikker på noe ComboBox, så endres panelet under. F.eks hvis
         * man trykker på e-post som alarm, så kommer det opp et textfield hvor
         * man skriver inn andresse.
         * @param e
         */
        public void actionPerformed(ActionEvent e) {
            JComboBox jcb = (JComboBox) e.getSource();
            selectedType = jcb.getSelectedIndex();
            //updateRightBoxEdit(selectedType);
            // vil oppdatere mid-pane i editnotificationpanel
            JComboBox jb = (JComboBox)e.getSource();
            JPanel jp = (JPanel)jb.getParent();
            EditNotificationPanel enp = (EditNotificationPanel)jp.getParent();
            enp.redrawMiddlePane(selectedType);
        }
    }

    /**
     * Lytter til klikk i JList med varslinger.
     */
    private class ListListener implements ListSelectionListener {
        private int selectedNotification;
        private Object selectedNotificationObject;

        public ListListener() {
            super();
        }

        /**
         * Oppdaterer høyreboksen ettersom hva man har trykket på i JList over varslinger
         * @param e
         */
        public void valueChanged(ListSelectionEvent e) {
            JList jlt = (JList) e.getSource();
            selectedNotification = jlt.getSelectedIndex();
            selectedNotificationObject = jlt.getSelectedValue();
            updateRightBox(selectedNotification);
        }

        /**
         *
         * @return Returnerer den valgte varslingen som en int
         */
        public int getSelectedNotification() {
            return selectedNotification;
        }

        /**
         *
         * @return Returnerer den valgte varslingen som en string
         */
        public String getSelectedNotificationString() {
            return selectedNotificationObject.toString();
        }
    }

    /**
     * Knappelytter
     */
    private class ButtonListener implements ActionListener {
        public ButtonListener() {
            super();
        }

        /**
         * Utfører operasjoner ut i fra knappene "new", "edit", "delete", "browse" og "finished".
         * @param event
         */
        public void actionPerformed(ActionEvent event) {
            if(event.getActionCommand().equalsIgnoreCase(newButtonString)) {
                updateRightBoxEdit(-1);
            } else if (event.getActionCommand().equalsIgnoreCase(editButtonString)) {
                updateRightBoxEdit(listListener.getSelectedNotification());
            } else if(event.getActionCommand().equalsIgnoreCase(deleteButtonString)) {
                String[] buttons = {"Delete", "Cancel"};
                int i = JOptionPane.showOptionDialog(null, "Are you sure you want to delete this timer?", "Delete timer", JOptionPane.OK_CANCEL_OPTION,
                        JOptionPane.QUESTION_MESSAGE, null,buttons, buttons[1]);
                if (i == 0) {
                    deleteNotification(listListener.getSelectedNotification());
                }


            } else if(event.getActionCommand().equalsIgnoreCase(browseButtonString)) {
                JButton jb = (JButton)event.getSource();
                JPanel jp = (JPanel)jb.getParent();
                EditNotificationPanel enp = (EditNotificationPanel)jp.getParent();
                enp.setFilePath(browseForFile());
            } else if(event.getActionCommand().equalsIgnoreCase(finishedButtonString)) {
                JButton jb = (JButton)event.getSource();
                JPanel jp = (JPanel)jb.getParent();
                EditNotificationPanel enp = (EditNotificationPanel)jp.getParent();
                updateTimer(enp);
            } 
        }


    }

    /**
     * Oppdaterer timeren etter at endringer er gjort.
     * @param enp
     */
    private void updateTimer(EditNotificationPanel enp) {
            boolean bad = false;
            boolean update = true;
            boolean dupe = false;
            if (enp.getData().equals("")) update = false; // det var tomt fra før, mao snakk in NY varsling
            if (enp.getName().equals("")) bad = true; // ikke satt navn -> bad
            if (MAIL == enp.getTypeList()) {
                if (enp.getEpostField().equals("")) bad = true;
            }
            if (TWITTER == enp.getTypeList()) {
                if (enp.getTwitterUserName().equals("")) bad = true;
            }
            if (SOUND == enp.getTypeList()) {
                if (enp.getFilePath().equals("")) bad = true;
            }
            if (bad) { showMessageDialog(null, "Alert", "Error", JOptionPane.ERROR_MESSAGE);}
            String[] str = fancyTimerLogikk.getNotificationList();
            for (String s: str) {
                if (s.trim().equals(enp.getName())) {
                    if (s.trim().equals(enp.getData())) break;
                    showMessageDialog(null, "A notification with this name already exists.", "Alert", JOptionPane.ERROR_MESSAGE);
                    dupe = true;
                }
            }
            if (!bad && !dupe) {
                LNotification ln = new LNotification("BUGBUGBUG");
                if (MAIL == enp.getTypeList() ) {
                    ln = new LNMail(enp.getName(),enp.getEpostField());
                }
                if (TWITTER == enp.getTypeList()) {
                    ln = new LNTwitter(enp.getName(), enp.getTwitterUserName());
                }
                if (SOUND == enp.getTypeList()) {
                    ln = new LNSound(enp.getName(), enp.getFilePath());
                }
                if(update) {
                    int t = 0;
                    str = fancyTimerLogikk.getNotificationList();
                    for (String s: str) {
                        if (s.equals(enp.getData())) {fancyTimerLogikk.deleteNotification(t); break;}
                        t++;
                    }
                }
                fancyTimerLogikk.addNotification(ln);
                refreshNotifications();
                fancyTimerLogikk.saveAllData();
            }
        }


    /**
     * Returnerer en string med den komplette stien til fila som velges
     * @return En sti til fila som velges
     */
    private String browseForFile() {
        JFileChooser jFileChooser = new JFileChooser();
        Mp3FileFilter filter = new Mp3FileFilter();
        jFileChooser.setFileFilter(filter);
        String str = "";
        if(jFileChooser.showOpenDialog(this) == JFileChooser.APPROVE_OPTION)
            {
             str = jFileChooser.getSelectedFile().getAbsolutePath();
            }
        return str;
    }

    /**
     * Klassen sjekker om fila man velger faktisk er en mp3-fil
     */
    private class Mp3FileFilter extends javax.swing.filechooser.FileFilter {
        public boolean accept(File f) {
            return f.isDirectory() || f.getName().toLowerCase().endsWith(".mp3");
        }

        public String getDescription() {
            return ".mp3 files";
        }
    }

    /**
     * Metoden sletter en varsling
     * @param selectedNotification Den valgte varslingen
     */
    private void deleteNotification(int selectedNotification) {
        fancyTimerLogikk.deleteNotification(selectedNotification);
        refreshNotifications();
        
    }
}
